#!/bin/bash

# 测试Dify API连接

echo "=========================================="
echo "Dify API 连接测试"
echo "=========================================="
echo ""

API_KEY="app-4tJS69FUxtIuhftpidIHCj09"
BASE_URL="http://localhost/v1"

echo "配置信息："
echo "  Base URL: $BASE_URL"
echo "  API Key: ${API_KEY:0:10}..."
echo ""

echo "1. 测试Dify服务是否可访问..."
if curl -s http://localhost > /dev/null; then
    echo "✓ Dify服务可访问"
else
    echo "✗ Dify服务不可访问"
    exit 1
fi
echo ""

echo "2. 直接测试Dify Chat API..."
echo "请求数据："
cat << EOF
{
  "inputs": {},
  "query": "你好",
  "response_mode": "blocking",
  "user": "test-user"
}
EOF
echo ""

response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/chat-messages" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {},
    "query": "你好",
    "response_mode": "blocking",
    "user": "test-user"
  }')

http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

echo "HTTP状态码: $http_code"
echo "响应内容:"
echo "$body" | head -c 500
echo ""
echo ""

if [ "$http_code" = "200" ]; then
    echo "✓ Dify API调用成功！"
elif [ "$http_code" = "401" ]; then
    echo "✗ 401 Unauthorized - API密钥无效或未授权"
    echo "  请检查："
    echo "  1. API密钥是否正确"
    echo "  2. 应用类型是否为'聊天助手'"
elif [ "$http_code" = "400" ]; then
    echo "✗ 400 Bad Request - 请求格式错误"
    echo "  可能原因："
    echo "  1. 应用需要必填的inputs参数"
    echo "  2. API端点不正确"
    echo "  3. 请求格式不符合要求"
    echo ""
    echo "  建议："
    echo "  1. 在Dify控制台检查应用的'提示词编排'设置"
    echo "  2. 查看是否有必填的输入变量"
    echo "  3. 尝试使用'completion-messages'端点（如果是文本生成应用）"
else
    echo "✗ 错误 (HTTP $http_code)"
fi

echo ""
echo "=========================================="
echo "3. 测试通过后端API..."
echo "=========================================="
echo ""

response2=$(curl -s -w "\n%{http_code}" -X POST "http://localhost:8080/api/qa/ask" \
  -H "Content-Type: application/json" \
  -d '{"question":"你好","userId":1}')

http_code2=$(echo "$response2" | tail -n1)
body2=$(echo "$response2" | sed '$d')

echo "HTTP状态码: $http_code2"
echo "响应内容:"
echo "$body2" | head -c 500
echo ""

if [ "$http_code2" = "200" ]; then
    echo "✓ 后端API调用成功！"
else
    echo "✗ 后端API调用失败"
fi
